<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">API 管理</h1>
        <p class="page-description">管理和配置您的 API 接口</p>
      </div>
      <div class="header-actions">
        <a-button type="primary" @click="showCreateApi = true">
          <template #icon><PlusOutlined /></template>
          创建 API
        </a-button>
      </div>
    </div>

    <advanced-search
      :fields="searchFields"
      :initial-values="searchValues"
      @search="handleSearch"
      @reset="handleReset"
    />

    <data-table
      :columns="columns"
      :data-source="apis"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #toolbar>
        <a-space>
          <a-select
            v-model:value="filters.method"
            placeholder="请求方法"
            style="width: 120px"
            allow-clear
          >
            <a-select-option value="GET">GET</a-select-option>
            <a-select-option value="POST">POST</a-select-option>
            <a-select-option value="PUT">PUT</a-select-option>
            <a-select-option value="DELETE">DELETE</a-select-option>
          </a-select>
          <a-select
            v-model:value="filters.status"
            placeholder="状态"
            style="width: 120px"
            allow-clear
          >
            <a-select-option value="active">正常运行</a-select-option>
            <a-select-option value="inactive">已停用</a-select-option>
            <a-select-option value="error">错误</a-select-option>
          </a-select>
        </a-space>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'method'">
          <a-tag :color="getMethodColor(record.method)">
            {{ record.method }}
          </a-tag>
        </template>
        <template v-if="column.key === 'status'">
          <a-badge
            :status="getStatusType(record.status)"
            :text="getStatusText(record.status)"
          />
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" @click="handleTest(record)">
              <template #icon><PlayCircleOutlined /></template>
              测试
            </a-button>
            <a-button type="link" @click="handleEdit(record)">
              <template #icon><EditOutlined /></template>
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这个 API 吗？"
              @confirm="handleDelete(record)"
            >
              <a-button type="link" danger>
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </data-table>

    <form-modal
      v-model:open="showCreateApi"
      :title="editingApi ? '编辑 API' : '创建 API'"
      :loading="submitting"
      :rules="apiRules"
      :initial-values="apiForm"
      @submit="handleSubmit"
    >
      <a-form-item label="API 名称" name="name">
        <a-input v-model:value="apiForm.name" placeholder="请输入 API 名称" />
      </a-form-item>
      <a-form-item label="请求方法" name="method">
        <a-select v-model:value="apiForm.method" placeholder="请选择请求方法">
          <a-select-option value="GET">GET</a-select-option>
          <a-select-option value="POST">POST</a-select-option>
          <a-select-option value="PUT">PUT</a-select-option>
          <a-select-option value="DELETE">DELETE</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="API 路径" name="path">
        <a-input v-model:value="apiForm.path" placeholder="请输入 API 路径" />
      </a-form-item>
      <a-form-item label="数据库连接" name="connectionId">
        <a-select
          v-model:value="apiForm.connectionId"
          placeholder="请选择数据库连接"
          :loading="loadingConnections"
        >
          <a-select-option
            v-for="conn in connections"
            :key="conn.id"
            :value="conn.id"
          >
            {{ conn.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="SQL 查询" name="query">
        <a-textarea
          v-model:value="apiForm.query"
          placeholder="请输入 SQL 查询语句"
          :rows="4"
        />
      </a-form-item>
    </form-modal>

    <a-modal
      v-model:open="showTestResult"
      title="API 测试结果"
      :footer="null"
      width="600px"
    >
      <div class="test-result">
        <div class="result-header">
          <a-tag :color="testResult.success ? 'success' : 'error'">
            {{ testResult.success ? '成功' : '失败' }}
          </a-tag>
          <span class="result-time">{{ testResult.time }}ms</span>
        </div>
        <a-divider />
        <div class="result-content">
          <pre>{{ JSON.stringify(testResult.data, null, 2) }}</pre>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useApiStore } from '../stores/api'
import { useDatabaseStore } from '../stores/database'
import { useAppStore } from '../stores/app'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  PlayCircleOutlined
} from '@ant-design/icons-vue'
import DataTable from '../components/DataTable.vue'
import FormModal from '../components/FormModal.vue'
import AdvancedSearch from '../components/AdvancedSearch.vue'

const apiStore = useApiStore()
const databaseStore = useDatabaseStore()
const appStore = useAppStore()

const loading = ref(false)
const loadingConnections = ref(false)
const submitting = ref(false)
const showCreateApi = ref(false)
const showTestResult = ref(false)
const editingApi = ref(null)
const connections = ref([])

const apis = ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

const filters = ref({
  method: undefined,
  status: undefined,
  search: ''
})

const apiForm = ref({
  name: '',
  method: 'GET',
  path: '',
  connectionId: undefined,
  query: ''
})

const testResult = ref({
  success: false,
  time: 0,
  data: null
})

const searchValues = ref({
  keyword: '',
  method: undefined,
  status: undefined,
  dateRange: undefined
})

const searchFields = [
  {
    name: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '搜索 API 名称或路径'
  },
  {
    name: 'method',
    label: '请求方法',
    type: 'select',
    placeholder: '选择请求方法',
    options: [
      { label: 'GET', value: 'GET' },
      { label: 'POST', value: 'POST' },
      { label: 'PUT', value: 'PUT' },
      { label: 'DELETE', value: 'DELETE' }
    ]
  },
  {
    name: 'status',
    label: '状态',
    type: 'select',
    placeholder: '选择状态',
    options: [
      { label: '活跃', value: 'active' },
      { label: '禁用', value: 'disabled' },
      { label: '错误', value: 'error' }
    ]
  },
  {
    name: 'dateRange',
    label: '创建时间',
    type: 'dateRange',
    placeholder: ['开始日期', '结束日期'],
    advanced: true
  }
]

const columns = [
  {
    title: 'API 名称',
    dataIndex: 'name',
    key: 'name',
    sorter: true
  },
  {
    title: '请求方法',
    dataIndex: 'method',
    key: 'method',
    width: 100
  },
  {
    title: 'API 路径',
    dataIndex: 'path',
    key: 'path'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

const apiRules = {
  name: [{ required: true, message: '请输入 API 名称' }],
  method: [{ required: true, message: '请选择请求方法' }],
  path: [{ required: true, message: '请输入 API 路径' }],
  connectionId: [{ required: true, message: '请选择数据库连接' }],
  query: [{ required: true, message: '请输入 SQL 查询语句' }]
}

const getMethodColor = (method) => {
  const colors = {
    GET: 'blue',
    POST: 'green',
    PUT: 'orange',
    DELETE: 'red'
  }
  return colors[method] || 'default'
}

const getStatusType = (status) => {
  const types = {
    active: 'success',
    inactive: 'default',
    error: 'error'
  }
  return types[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    active: '正常运行',
    inactive: '已停用',
    error: '错误'
  }
  return texts[status] || status
}

const handleTableChange = (pag, filters, sorter) => {
  pagination.value = pag
  fetchAPIs()
}

const handleSearch = (values) => {
  Object.assign(searchValues.value, values)
  pagination.value.current = 1
  fetchAPIs()
}

const handleReset = () => {
  Object.keys(searchValues.value).forEach(key => {
    searchValues.value[key] = undefined
  })
  pagination.value.current = 1
  fetchAPIs()
}

const handleEdit = (record) => {
  editingApi.value = record
  apiForm.value = { ...record }
  showCreateApi.value = true
}

const handleDelete = async (record) => {
  try {
    await apiStore.deleteAPI(record.id)
    appStore.success('删除成功')
    fetchAPIs()
  } catch (error) {
    appStore.error('删除失败')
  }
}

const handleTest = async (record) => {
  try {
    const result = await apiStore.testAPI(record.id)
    testResult.value = {
      success: true,
      time: result.time,
      data: result.data
    }
    showTestResult.value = true
  } catch (error) {
    testResult.value = {
      success: false,
      time: 0,
      data: error.message
    }
    showTestResult.value = true
  }
}

const handleSubmit = async (values) => {
  submitting.value = true
  try {
    if (editingApi.value) {
      await apiStore.updateAPI(editingApi.value.id, values)
      appStore.success('更新成功')
    } else {
      await apiStore.createAPI(values)
      appStore.success('创建成功')
    }
    showCreateApi.value = false
    fetchAPIs()
  } catch (error) {
    appStore.error(editingApi.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
    editingApi.value = null
    apiForm.value = {
      name: '',
      method: 'GET',
      path: '',
      connectionId: undefined,
      query: ''
    }
  }
}

const fetchConnections = async () => {
  loadingConnections.value = true
  try {
    connections.value = await databaseStore.fetchConnections()
  } catch (error) {
    appStore.error('获取数据库连接失败')
  } finally {
    loadingConnections.value = false
  }
}

const fetchAPIs = async () => {
  loading.value = true
  try {
    const { data, total } = await apiStore.fetchAPIs({
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...filters.value
    })
    apis.value = data
    pagination.value.total = total
  } catch (error) {
    appStore.error('获取 API 列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchAPIs()
  fetchConnections()
})
</script>

<style scoped>
.page-container {
  padding: var(--spacing-lg);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--heading-color);
  margin: 0;
}

.page-description {
  font-size: 14px;
  color: var(--text-color-secondary);
  margin: var(--spacing-xs) 0 0;
}

.test-result {
  padding: var(--spacing-md);
}

.result-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.result-time {
  color: var(--text-color-secondary);
  font-size: 14px;
}

.result-content {
  margin-top: var(--spacing-md);
  background: var(--background-color-light);
  padding: var(--spacing-md);
  border-radius: var(--border-radius-base);
  max-height: 400px;
  overflow: auto;
}

.result-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 暗色主题适配 */
[data-theme='dark'] .result-content {
  background: var(--background-color-dark);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .page-container {
    padding: var(--spacing-md);
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }

  .header-actions {
    width: 100%;
  }

  .header-actions .ant-btn {
    width: 100%;
  }
}
</style> 